package game.module.mj.processor;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.mj.bean.MjRound;
import game.module.mj.logic.MjDataManager;
import game.module.mj.logic.MjLogic;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageMj.C2SMJReady;
import lua.LuaMessageMj.PushMjReady;
import lua.LuaMessageMj.S2CMJReady;

/**
 * 
 * @author llee
 *
 */
@MsgCodeAnn(msgcode = C2SMJReady.id, accessLimit = 500)
public class MjReadyProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(MjReadyProcessor.class);

	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw requestMessage) throws Exception {

		int playerId = playingRole.getId();
        
		logger.info("mj room ready,player={}",playerId);
		
		MjRound mjRound = MjDataManager.getInstance().getMjRoom(playerId);
		if(mjRound == null) {
			S2ErrorCode respMsg = new S2ErrorCode(201);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		S2CMJReady respMsg = new S2CMJReady();
		playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
		synchronized (mjRound) {
			MjLogic mjlogic = MjLogic.getInstance();
			// logger.info("Mj room connect,sessionId={}",mjRound );
			Set<Integer> enter_player = mjRound.getEnter_player();
			enter_player.add(playerId);
			logger.info("Mj room ready ready_player={}",  enter_player);
			if (enter_player.size() == 4) {
				logger.info("mj  start ");
				mjlogic.GameStart(mjRound); // 当四个人都连接上房间服务器后，系统开始自动摇色子和自动补花和金牌的确定
			}
		}
		PushMjReady pushMsg = new PushMjReady();
		List<Integer> players = new ArrayList<Integer>();
		pushMsg.player_index = (byte) players.indexOf(playerId);
		for(Integer aPlayer:players) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayer);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
		
		
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

}
